/*
 * by cansik / Florian
 * Datum: 09.06.2009
 * Zeit: 10:07
 * 
 *
 */
using System;
using System.Collections.Generic;
using CML;

namespace sEmit.Core
{
	/// <summary>
	/// Configuration Class for CML Files
	/// </summary>
	public class Configurator
	{
		public CMLWriter writer {get; set;}
		public CMLReader reader {get; set;}
		public string ConfigFile {get; set;}
		List<CMLElement> elements;
		
		public Configurator(string configfile)
		{
			writer = new CMLWriter();
			ConfigFile = configfile;
			elements = new List<CMLElement>();
		}
		
		public bool Read()
		{
			try
			{
				reader = new CMLReader(ConfigFile);
				reader.ReadFile(false);
				reader.Close();
				
				elements = new List<CMLElement>(reader.ElementsList);
				
				return true;
			}
			catch (Exception)
			{
				return false;
			}
		}
		public string Get(string element, string attribut)
		{
			return reader.GetElement(element).Attributes[attribut];
		}
		
		public string[] GetValues(string element)
		{
			CMLElement eTemp = reader.GetElement(element);
			string[] values = new string[eTemp.Attributes.Count];
			int counter = 0;
			
			foreach(string v in eTemp.Attributes.Keys)
			{
				values[counter] = eTemp.Attributes[v];
				counter++;
			}
			
			return values;
		}
		
		public void Save()
		{
			CopyToWriter();
			writer.Create(ConfigFile);
			writer.SaveAndClose(false);
			writer = new CMLWriter();
		}
		
		public void ChangeAttribut(string element, string attribute, string value)
		{
			CMLElement oE = new CMLElement(element);
			CMLElement tE = GetElement(element);
			
			foreach(string k in tE.Attributes.Keys)
			{
				CMLAttribut nA = new CMLAttribut();
				if (k == attribute)
				{
					nA.Name = k;
					nA.Value = value;
				}
				else
				{
					nA.Name = k;
					nA.Value = tE.Attributes[k];
				}
				oE.AddAttribut(nA);
			}
			
			oE.Save();
			elements.Remove(tE);
			elements.Add(oE);
		}
		
		private CMLElement GetElement(string name)
		{
			foreach (CMLElement e in elements)
			{
				if (e.Name == name)
				{
					return e;
				}
			}
			return new CMLElement(name);
		}
		
		public void ChangeElement(CMLElement element)
		{
			elements.Remove(GetElement(element.Name));
			elements.Add(element);
		}
		
		private void CopyToWriter()
		{
			foreach(CMLElement e in elements)
			{
				writer.AddElement(e);
			}
		}
	}
}
